import argparse
import os.path as osp
import os
import json
import glob
import shutil
import time
import re

# https://github.com/robinmoisson/staticrypt
# python bcs.py -s D:\BaiduSyncdisk\notebook\nlper -o C:\Users\xzh\Desktop\notes
#

parser = argparse.ArgumentParser()
parser.add_argument("-s", help="输入路经", default="DeepBlog")
parser.add_argument("-o", help="输出目录", default="deepblog_o")
parser.add_argument("--type", help="""设置生成的文件格式。默认为arduino。即支持8.3短文件名的格式。其他类型包括：
+ windows : 源文件对应的文件名。
arduino格式会将某文件夹下的文件按照0，1，2这样排列下去，index文件为0。assets文件夹不会设置。
""", default="windows")
parser.add_argument("--suffix", help="工作目录", default="")

#  http://ysuxzh.com/blog/

indexpage = """<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>
    <body>
        <css>
            <link rel="stylesheet" href="/notes/face.css">
        </css>
        <title>DeepBlog</title>
        <div id="information">
            <p>栏目：主目录</p><div id="separatrix"></div>
            {0}
        </div>
        <div id="column" style="text-align: center;">
            <div class="row" style="font-size: large;margin:0 auto;line-height:90px;">
            {1}
        </div>
        <div id="page"><iframe src="{2}.html" height="99%" width="100%" style="border:0"></iframe></div>
    </body>
</html>"""


def compile_(source, info, indent=4):
    print(" " * (indent - 4), "check for", source)
    pagelist = list()
    columnlist = list()
    for file in glob.glob(osp.join(source, "*")):
        if osp.isfile(file):
            filename = osp.split(file)[-1][:-3]
            mtime = int(osp.getmtime(file))
            date = time.strftime("%Y-%m-%d", time.localtime(mtime))
            pagelist.append((date, filename))
            if file in info:
                if mtime > info[file]:
                    outpath = osp.splitext(o + file[len(s):])[0] + ".html"
                    os.system("md2html.bat %s %s" % (file, outpath))
                    print(" " * indent, "compile", file)
                    info[file] = mtime
            else:
                outpath = osp.splitext(o + file[len(s):])[0] + ".html"
                os.system("md2html.bat %s %s" % (file, outpath))
                print(" " * indent, "compile", file)
                info[file] = mtime
        else:
            if osp.splitext(file)[1] != ".assets":
                outpath = o + file[len(s):]
                if not osp.isdir(outpath):
                    os.mkdir(outpath)
                filename = osp.split(file)[-1]
                columnlist.append(filename)
                compile_(file, info, indent + 4)
            else:
                outpath = o + file[len(s):]
                if osp.isdir(outpath):
                    shutil.rmtree(outpath)
                shutil.copytree(file, outpath)

    # pageproduct
    pagelist = sorted(pagelist, key=lambda x: x[0])
    pagelist_code = ""
    columnlist_code = ""
    showing_page = ""

    for date, filename in pagelist:
        pagelist_code += '<div class="blog_title"><a href="%s.html">%s</a><p class="blog_explain">%s</p></div>\n'\
                         % (filename, filename, date)
        if showing_page != "栏目介绍":
            showing_page = filename

    for column in columnlist:
        columnlist_code += '<div class="col-md-2"><a href="%s/index.html">%s</a></div>' % (column, column)

    pagecode = indexpage.format(pagelist_code, columnlist_code, showing_page)

    with open(osp.join(o + source[len(s):], "index.html"), mode="w", encoding="utf8") as indexfile:
            indexfile.write(pagecode)


args = parser.parse_args()
s, o = args.s, args.o
filename_type = args.type
suffix = args.suffix

if osp.isfile(osp.join(s,".info")):
    with open(osp.join(s,".info"), mode='r') as file:
        info = json.load(file)
else:
    info = dict()

# shutil.rmtree(o)
if not osp.isdir(o):
    os.mkdir(o)

compile_(s, info)

if filename_type == "arduino":
    if suffix:
        os.system("convert.py --suffix %s" % suffix)
    else:
        os.system("convert.py")